package ren.xbcr.schoolbus.client.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;

import java.sql.Driver;

import ren.xbcr.schoolbus.client.R;
import ren.xbcr.schoolbus.client.domain.BusDriver;
import ren.xbcr.schoolbus.client.domain.DriverRating;
import ren.xbcr.schoolbus.client.service.SchoolBusService;
import ren.xbcr.schoolbus.client.util.Constants;

/**
 * Created by Jian on 2015/12/5.
 */
public class RatingDriverFragment extends DialogFragment {

    public interface NoticeDialogListener {
        public void onDialogConfirmClick(DialogFragment dialog);

        public void onDialogCancelClick(DialogFragment dialog);
    }

    private static RatingBar mRatingBar;

    // Use this instance of the interface to deliver action events
    NoticeDialogListener mListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener = (NoticeDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement NoticeDialogListener");
        }
    }

    public static RatingDriverFragment newInstance(Long driverId, Integer ratingNumber, String telephoneNum, String driverName,
                                                   RatingBar ratingBar) {
        RatingDriverFragment f = new RatingDriverFragment();

        mRatingBar = ratingBar;
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putLong(Constants.BUNDLE_DRIVER_ID, driverId);
        args.putString(Constants.BUNDLE_DRIVER_NAME, driverName);
        args.putInt(Constants.RATING_NUMBER, ratingNumber);
        args.putString(Constants.USER_TELEPHONE, telephoneNum);
        f.setArguments(args);

        return f;
    }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Long driverId = getArguments().getLong(Constants.BUNDLE_DRIVER_ID);
        final String driverName = getArguments().getString(Constants.BUNDLE_DRIVER_NAME);
        final Integer ratingNumber = getArguments().getInt(Constants.RATING_NUMBER);
        final String telephoneNum = getArguments().getString(Constants.USER_TELEPHONE);

        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View ratingView = inflater.inflate(R.layout.dialog_rating_driver, null);

        builder.setView(ratingView)
                .setMessage(String.format(getString(R.string.display_rating_info), driverName, ratingNumber))
                .setPositiveButton(R.string.rating_btn, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        EditText descriptionEditor = (EditText)ratingView.findViewById(R.id.rating_driver_description_editor);
                        DriverRating driverRating = new DriverRating(ratingNumber, driverId, telephoneNum, descriptionEditor.getText().toString());

                        PostRatingTask postRatingTask = new PostRatingTask(driverRating);
                        postRatingTask.execute((Void) null);
                        mListener.onDialogConfirmClick(RatingDriverFragment.this);

                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        mListener.onDialogCancelClick(RatingDriverFragment.this);
                    }
                })
                .setOnKeyListener(new DialogInterface.OnKeyListener() {

                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode,
                                         KeyEvent event) {
                        // TODO Auto-generated method stub
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                            mListener.onDialogCancelClick(RatingDriverFragment.this);

                        }
                        return false;
                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }

    public static RatingBar getRatingBar(){
        return mRatingBar;
    }

    public class PostRatingTask extends AsyncTask<Void, Void, Boolean> {

        private DriverRating mDriverRating;

        public PostRatingTask(DriverRating driverRating) {
            mDriverRating = driverRating;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            Boolean isLoginSuccess = false;
            // Simulate network access.
            SchoolBusService schoolBusService = new SchoolBusService();
            schoolBusService.postDriverRating(mDriverRating);

            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {

/*        mTeleAuthTask = null;
//            showProgress(false);

        if (success) {
            finish();
        } else {
            mPasswordView.setError(getString(R.string.error_incorrect_login));
            mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled() {
/*        mTeleAuthTask = null;
        showProgress(false);*/
        }
    }
}
